import { useRef, useState, useEffect } from "react";
import type { FC } from "react";
import type { AiModelResponse } from "../services/chat/geiAiModel";

interface ModelSelectorProps {
  selectedModel: AiModelResponse;
  models: AiModelResponse[];
  onModelChange: (model: AiModelResponse) => void;
}

// 可能的模型结构，用于类型安全的属性访问
interface PossibleModelStructure {
  accessCode?: string;
  enabled?: boolean;
  modeName?: string;
  modelName?: string;
  name?: string;
  model?: string;
  modeType?: string;
  modelType?: string;
  description?: string;
  type?: string;
  tags?: string[];
  [key: string]: unknown; // 允许其他未知属性
}

const ModelSelector: FC<ModelSelectorProps> = ({
  selectedModel,
  models,
  onModelChange,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const [dropdownPosition, setDropdownPosition] = useState<{
    top: number;
    left: number;
  } | null>(null);

  // 计算弹出层位置
  const calculatePosition = () => {
    if (triggerRef.current && isOpen) {
      const rect = triggerRef.current.getBoundingClientRect();
      const top = rect.top - 10; // 距离按钮顶部10px
      const left = rect.left;
      setDropdownPosition({ top, left });
    }
  };

  // 监听弹出状态变化
  useEffect(() => {
    if (isOpen) {
      calculatePosition();
      window.addEventListener("resize", calculatePosition);
      window.addEventListener("scroll", calculatePosition);
    }

    return () => {
      window.removeEventListener("resize", calculatePosition);
      window.removeEventListener("scroll", calculatePosition);
    };
  }, [isOpen]);

  // 过滤启用的模型 - 添加安全检查
  const enabledModels = models.filter((model) =>
    // 如果model.enabled不存在或不是布尔值，则默认视为已启用
    model.enabled === undefined ? true : Boolean(model.enabled)
  );

  // 安全地获取模型名称
  const getModelName = (model: PossibleModelStructure): string => {
    // 按优先级尝试不同的可能字段名
    if (model?.modeName) return model.modeName;
    if (model?.modelName) return model.modelName;
    if (model?.name) return model.name;
    if (model?.model) return model.model;
    if (model?.accessCode) return model.accessCode; // 使用accessCode作为后备
    return "未命名模型";
  };

  // 安全地获取模型描述
  const getModelDescription = (
    model: PossibleModelStructure
  ): string | null => {
    if (model?.modeType) return model.modeType;
    if (model?.modelType) return model.modelType;
    if (model?.description) return model.description;
    if (model?.type) return model.type;
    return null;
  };

  // 关闭下拉菜单的处理函数
  const handleClose = () => {
    setIsOpen(false);
    setDropdownPosition(null);
  };

  // 点击外部区域关闭菜单
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (
        isOpen &&
        triggerRef.current &&
        !triggerRef.current.contains(e.target as Node)
      ) {
        const dropdown = document.getElementById("model-dropdown");
        if (dropdown && !dropdown.contains(e.target as Node)) {
          handleClose();
        }
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen]);

  return (
    <div className="relative inline-block text-left">
      <button
        ref={triggerRef}
        type="button"
        className="inline-flex items-center justify-center px-3 py-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700"
        onClick={() => setIsOpen(!isOpen)}
        aria-haspopup="true"
        aria-expanded={isOpen}
        style={{ minWidth: "120px" }}
      >
        <span className="truncate mr-1">
          {selectedModel
            ? getModelName(selectedModel as unknown as PossibleModelStructure)
            : "选择模型"}
        </span>
        <svg
          className={`w-4 h-4 flex-shrink-0 transition-transform duration-200 ${
            isOpen ? "transform rotate-180" : ""
          }`}
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 20 20"
          fill="currentColor"
          aria-hidden="true"
        >
          <path
            fillRule="evenodd"
            d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
            clipRule="evenodd"
          />
        </svg>
      </button>

      {isOpen && dropdownPosition && (
        <div
          id="model-dropdown"
          className="fixed z-50 w-56 rounded-md bg-white dark:bg-gray-800 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
          style={{
            position: "fixed",
            top: `${dropdownPosition.top - 4}px`,
            left: `${dropdownPosition.left}px`,
            transform: "translateY(-100%)",
            marginTop: "-8px",
          }}
        >
          <div
            className="py-1"
            role="menu"
            aria-orientation="vertical"
            aria-labelledby="model-button"
          >
            {enabledModels && enabledModels.length > 0 ? (
              enabledModels.map((model, index) => {
                const safeModel = model as unknown as PossibleModelStructure;
                // 提取唯一标识符
                const modelId = safeModel.accessCode || `model-${index}`;
                // 提取模型名称
                const modelName = getModelName(safeModel);
                // 提取模型描述
                const modelDesc = getModelDescription(safeModel);

                // 确定是否为选中项
                const isSelected =
                  selectedModel &&
                  ((selectedModel.accessCode &&
                    selectedModel.accessCode === safeModel.accessCode) ||
                    getModelName(
                      selectedModel as unknown as PossibleModelStructure
                    ) === modelName);

                return (
                  <button
                    key={modelId + index}
                    className={`
                      w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700
                      ${
                        isSelected
                          ? "bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white"
                          : "text-gray-700 dark:text-gray-300"
                      }
                    `}
                    role="menuitem"
                    tabIndex={-1}
                    onClick={() => {
                      console.log("选择模型:", model);
                      onModelChange(model);
                      handleClose();
                    }}
                  >
                    <div>
                      <div className="font-medium">{modelName}</div>
                      {modelDesc && (
                        <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                          {modelDesc}
                        </div>
                      )}
                    </div>
                  </button>
                );
              })
            ) : (
              <div className="px-4 py-2 text-sm text-gray-500 dark:text-gray-400">
                没有可用模型
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default ModelSelector;
